import { Component, OnInit } from '@angular/core';
import { NziModalService } from 'ng-zorro-iop/modal/nzi-modal.service';
import { NzMessageService } from "ng-zorro-antd";
import { FcsService } from "../../service/fcs.service";
import { DomainCreateComponent } from '../create/domain-create.component';

@Component({
  selector: 'app-domain-list',
  templateUrl: './domain-list.component.html',
  styleUrls: ['./domain-list.component.less']
})
export class DomainListComponent implements OnInit {
  isLoading = true;
  pageNo = 1;
  pageSize = 10;
  totalCount = 0;
  domainList = [];

  constructor(
    private fcsService: FcsService,
    private modalService: NziModalService,
    private msgService: NzMessageService,
  ) { }

  ngOnInit() {
    this.getDomainList();
  }

  getDomainList() {
    this.isLoading = true;
    this.fcsService.getDomainList(this.pageNo, this.pageSize).subscribe(res => {
      this.totalCount = res.totalCount;
      this.pageNo = res.pageNo;
      this.pageSize = res.pageSize;
      this.domainList = res.data;
      this.isLoading = false;
    }, error => {
      this.isLoading = false;
    })
  }

  createDomain() {
    this.modalService.create({
      nzTitle: '创建自定义域名',
      nzMaskClosable: false,
      nzWidth: '7rem',
      nzContent: DomainCreateComponent,
      nzOnOk: async componentInstance => {
        let isSuccess = await componentInstance.submitForm();
        isSuccess && this.getDomainList();
        return isSuccess;
      },
    });
  }

  updateDomain(data) {
    this.modalService.create({
      nzTitle: '配置自定义域名',
      nzMaskClosable: false,
      nzWidth: '7rem',
      nzContent: DomainCreateComponent,
      nzComponentParams: { domainInstance: data },
      nzOnOk: async componentInstance => {
        let isSuccess = await componentInstance.submitForm();
        isSuccess && this.getDomainList();
        return isSuccess;
      },
    });
  }

  deleteDomain(data) {
    this.modalService.delete({
      nzTitle: '删除自定义域名',
      nzContentTitle: `确定删除自定义域名 <em>“${data.domainName}”</em> 吗？`,
      nzOnOk: () => {
        return new Promise((resolve, reject) => {
          this.fcsService.deleteDomain(data.id).subscribe(
            data => {
              if (data && data.code) {
                resolve(false);
                this.msgService.error(data.message || '删除失败！');
              } else {
                this.msgService.success('删除成功！');
                if (this.domainList.length <= 1) {
                  this.pageNo -= 1;
                  this.pageNo = this.pageNo <= 0 ? 1 : this.pageNo;
                }
                this.getDomainList();
                resolve(true);
              }
            },
            err => {
              resolve(false);
            });
        });
      },
      nzCancelText: '取消',
      nzOnCancel: () => { },
    });
  }

}
